<?php
class Delivery_Model_DbTable_Zonas
	extends Delivery_Model_DbTable_Abstract

{
	protected $_name = 'zonas';
	protected $_primary = 'idZona';
	
	public function select( $withFromPart = self::SELECT_WITHOUT_FROM_PART ){
	
		return  
			parent::select( $withFromPart )
					->from( $this->_name, array('idZona', 'idNegocio', 'nombre', 'precio', 'compraMinima'))					
					->columns(array('coordenadas'=>'asText(coordenadas)'));
	
	}
	
	public function insert( $zona ){
		
		return parent::insert(		
			$this->_fecha( $this->_getData( $zona ), true, true)
		);	
	}
	
	public function update( $zona ){
		
		$data = $this->_getData( $zona );
		
		return parent::update(
			$this->_fecha( $this->_getData( $zona ), false, true),
			array('idZona = ?' => $zona->idZona)		
		);
	}
	
	public function delete ( $zona )
	{
		return parent::delete(array('idZona = ?' => $zona->idZona));
	}
	
	
	
	public function getById( $idZona ){
		
		return 
			$this->_fetch(
				$this->select()->where('idZona = ?', $idZona, Zend_Db::INT_TYPE)
			);
	}
	
	public function getByNegocio( $idNegocio ){
		
		$select = $this->select();
		
		if ( is_int($idNegocio) ){
			$select->where('idNegocio = ?', $idNegocio, Zend_Db::INT_TYPE);
		} else {
			$select->where('idNegocio IN (?)', $idNegocio, Zend_Db::INT_TYPE);
		}
		
		return $this->_fetchAll($select);
	}
	
	
	public function getByDireccion( $idNegocio, $idDireccion ){

		$select2 = new Zend_Db_Select( $this->getAdapter() );
		$select2->from( 'direcciones', array('punto'))
		 		->join(	'cliente_direcciones','direcciones.idDireccion = cliente_direcciones.idDireccion', array())	
				->where('idDireccionCliente = ?', $idDireccion, Zend_Db::INT_TYPE); 
		
		$subQuery = $select2->assemble();

		return 
			$this->_fetch(
				$this->select( )
					->where('idNegocio = ?', $idNegocio, Zend_Db::INT_TYPE)
					->where("trueWithin (($subQuery), coordenadas)")
					->limit(1)
					->order("precio")
					->order("compraMinima")
			);
	}
	
	public function getNegociosByDireccion( $idDireccion ){

		$select2 = new Zend_Db_Select( $this->getAdapter() );
		$select2->from( 'direcciones', array('punto'))
				->where('idDireccion = ?', $idDireccion, Zend_Db::INT_TYPE); 
		
		$subQuery = $select2->assemble();
				
		return 
			$this->_db->fetchCol(
				parent::select( $withFromPart = self::SELECT_WITHOUT_FROM_PART )
					->from( $this->_name, array('idNegocio'))					
					->where("trueWithin (($subQuery), coordenadas)")
			);
	}
	
	
	
	protected function _getData( $zona )
	{
		$coordenadas = $this->_encodeZona( $zona->coordenadas );
		
		return array (
			'idNegocio'		=> $zona->idNegocio,
   			'nombre'		=> $zona->nombre,	   			
   			'precio'		=> $zona->precio,
   			'compraMinima'	=> $zona->compraMinima,
			'coordenadas'	=> new Zend_Db_Expr("GeomFromText('POLYGON(($coordenadas))')")
   		);
	} 
	
	protected function _fetch( $select )
	{					
		$row = $this->_db->fetchRow( $select );

		if ( ! empty( $row ) ){		
			$row['coordenadas']	= $this->_decodeZona( $row['coordenadas'] );
		}	
						
		return $row;
	} 
	
	protected function _fetchAll( $select )
	{
		$rowset = $this->_db->fetchAll( $select );

		foreach ( $rowset as &$row){
			$row['coordenadas']	= $this->_decodeZona( $row['coordenadas'] );
		
		}

		return $rowset;
	}
	
	protected function _encodeZona( $zona )
	{
		$zona[]= $zona[0];		
		$coordinates = '';
		
		foreach ($zona as $z){
			$coordinates.= implode(" ", $z) . ','; 
		}
		
		return rtrim($coordinates, ",");		
	}
	
	protected function _decodeZona( $zona )
	{
		$zona = str_replace("POLYGON((", '', $zona);
		$zona = str_replace("))", '', $zona);
		$zona = explode(',', $zona);
		array_pop($zona);
		
		foreach ($zona as &$z){
			$coordinates = explode(" ", $z); 
			$z = array(
				'lat' => $coordinates[0],
				'lon' => $coordinates[1]
			);		
		}
		
		return $zona;
	}
	
	
}